/*
 *  (C) Copyright 2008 Insula T.I. Ltda.
 * 
 *  This file is part of Vulcano.
 *
 *  Vulcano is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Lesser General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  Vulcano is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public License
 *  along with Vulcano.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.openinsula.vulcano.orm.dao.jpa;

import java.io.Serializable;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.LockModeType;

import org.openinsula.vulcano.orm.dao.Dao;
import org.openinsula.vulcano.orm.dao.query.DaoQuery;
import org.springframework.orm.jpa.JpaTemplate;
import org.springframework.orm.jpa.support.JpaDaoSupport;

/**
 * {@link Dao} implementation that uses Spring's {@link JpaDaoSupport}.
 * 
 * @author erdanielli
 * @author yanaga
 * @since 1.0
 * @see Dao
 * @see DaoQuery
 * @see EntityManager
 * @see JpaDaoSupport
 * @see JpaTemplate
 */
public class JpaDao extends JpaDaoSupport implements Dao {

	@Override
	public <T> T findById(Class<T> entityClass, Serializable id) {
		return getJpaTemplate().find(entityClass, id);
	}

	@Override
	public <T> T findUnique(DaoQuery<T> daoQuery) {
		List<T> queryList = find(daoQuery);

		int resultCount = queryList.size();

		if (resultCount > 1) {
			throw new IllegalStateException("Query did not return unique result!");
		}

		return (T) (resultCount == 0 ? null : queryList.get(0));
	}

	@Override
	public <T> List<T> find(DaoQuery<T> daoQuery) {
		throw new RuntimeException("JPA find not implemented yet!");
	}

	@Override
	public <T> T merge(T entity) {
		return getJpaTemplate().merge(entity);
	}

	@Override
	public void persist(Object... entities) {
		for (Object entity : entities) {
			getJpaTemplate().getEntityManager().persist(entity);
		}
	}

	@Override
	public void remove(Object... entities) {
		for (Object entity : entities) {
			getJpaTemplate().getEntityManager().remove(entity);
		}
	}

	@Override
	public void refresh(Object... entities) {
		for (Object entity : entities) {
			getJpaTemplate().getEntityManager().refresh(entity);
		}
	}

	@Override
	public void reattach(Object... entities) {
		for (Object entity : entities) {
			getJpaTemplate().getEntityManager().lock(entity, LockModeType.READ);
		}
	}

	@Override
	public void evict(Object... entities) {
		throw new RuntimeException("JPA evict not implemented yet!");
	}

	@Override
	public void clear() {
		getJpaTemplate().getEntityManager().clear();
	}

	@Override
	public void flush() {
		getJpaTemplate().getEntityManager().flush();
	}

}
